<template>
  <div :ref="domId" class="chart-container"></div>
</template>

<script lang="ts">
import { defineComponent, PropType } from 'vue';

import * as echarts from 'echarts/core';
import {
  TooltipComponent,
  TooltipComponentOption,
  LegendComponent,
  LegendComponentOption,
  GridComponent
} from 'echarts/components';
import { BarChart, BarSeriesOption } from 'echarts/charts';
import { LabelLayout } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([
  TooltipComponent,
  LegendComponent,
  BarChart,
  CanvasRenderer,
  LabelLayout,
  GridComponent
]);

type EChartsOption = echarts.ComposeOption<
  TooltipComponentOption | LegendComponentOption | BarSeriesOption
>;

interface RowData {
  category: string[];
  barData: number[];
}

const Component = defineComponent({
  props: {
    // 图表名称
    name: String,
    // 统计数据 - 通过API获取
    rowData: {
      type: Object as PropType<RowData>,
      required: true
    }
  },

  data() {
    return {
      // dom ID
      domId: 'chart-bar'
      // 图表数据
      // chartData: [] as ChartData[],
    };
  },

  watch: {
    // 监听图表数据
    rowData: {
      handler() {
        // 渲染图表
        this.renderChart();
      },
      deep: true
    }
  },

  methods: {
    // 渲染图表
    renderChart() {
      // 获取dom
      // const chartDom = document.getElementById(this.domId)!;
      const chartDom = this.$refs[this.domId] as HTMLElement;
      // 初始化dom
      const myChart = echarts.init(chartDom);
      // 配置图表数据
      let option: EChartsOption;

      option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          // data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
          data: this.rowData.category
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            type: 'bar',
            barWidth: '30%',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#2378f7' },
                  { offset: 0.7, color: '#2378f7' },
                  { offset: 1, color: '#83bff6' }
                ])
              }
            },
            // data: [120, 200, 150, 80, 70, 110, 130],
            data: this.rowData.barData
          }
        ]
      };

      // 绘制图表
      option && myChart.setOption(option);
    }
  }
});

export default Component;
</script>

<style lang="scss" scoped>
.chart-container {
  height: 400px;
}
</style>
